<?php
function tpl_page($total, $pageSize){
    $Page = new \Think\Page($total , $pageSize);
    $Page->rollPage = 10;
    $Page->setConfig('prev', '上一页');
    $Page->setConfig('next', '下一页');
    $Page->setConfig('first', '首页 ...');
    $Page->setConfig('last', '... 尾页');
    $show = $Page->show();
    return $show;
}

// 数组分页
function array_page($arr, $page, $pageSize){
    $offset = $pageSize * ($page - 1);
    return array_slice($arr, $offset, $pageSize);
}

function gotoPage($arr, $pageSize = 0, $parameter = 'Page'){
    if(empty($arr) || ! is_array($arr)) return [];
    $request_page = (int)I('get.'.$parameter);
    $page = $request_page > 1 ? $request_page : 1;
    $pageSize = (int)$pageSize > 0 ? (int)$pageSize : C('DEFAULT_PAGE_SIZE');
    $total = count($arr);
    $data = array_page($arr, $page, $pageSize);
    $pageshow = tpl_page($total, $pageSize);
    return empty($data) ? [] : array(
        'data' => $data,
        'page' => $pageshow
    );
}

//获取配置信息，存为 key => value 形式的数组
function getConfig($key = ''){
    $result = [];
    if( '' === $key ){
        $config_data = M('config')->field('key, value')->select();
        foreach( $config_data as $k => $v ){
            $result[$v['key']] = $v['value'];
        }
        return $result;
    }else{
        $map['key'] = $key;
        $config_data = M('config')->field('value')->where($map)->find();
        return $config_data['value'];
    }
}


// 计算订单总金额
function order_amount($amount, $price){
    if( is_numeric($amount) && is_numeric($price) ){
        return price((int)$amount * floatval($price), false);
    }
    return 0;
}

// 应结帐金额 - 订单金额 * 手续费
function order_balance($amount, $price){
    $order_amount = floatval(order_amount($amount, $price));
    $poundage = getConfig('POUNDAGE');
    return price($order_amount * (1 - floatval($poundage) / 100), false);
}

//空值时代替显示
function replacement($str, $replace = '未填写'){
    return empty($str) ? $replace : $str;
}

//订单时间为空时，可以使用自定义字符代替
function show_order_time($time, $replace = '未填写'){
    $r = replacement($time, $replace);
    return $r === $replace ? $replace : date('Y-m-d H:i:s', $time);
}

// 当前控制器名称
function controller_name(){
    $tmp = explode('/', CONTROLLER_NAME);
    return end($tmp);
}

// 订单状态文字描述
function order_status($status){
    $key = (int)$status;
    $status_text = C('ORDER_STATUS');
    if(isset($status_text[$key])){
        return $status_text[$status];
    }
    return '';
}

// 商品状态文字描述
function goods_status($status){
    $key = (int)$status;
    $status_text = C('GOODS_STATUS');
    if(isset($status_text[$key])){
        return $status_text[$status];
    }
    return '';
}